//
//  BHSportMainViewController.swift
//  BigHealth
//
//  Created by 蔺百好 on 2021/7/15.
//

import UIKit

class BHSportMainViewController: BHBaseViewController {
    lazy var headerView: BHSportMainHeaderView = {
        let view = BHSportMainHeaderView.loadFromXib()
        view.frame = CGRect(x: 0, y: UIScreen.begainY, width: UIScreen.width, height: BHSportMainHeaderView.height)
        view.delegate = self
        return view
    }()
    
    lazy var secView: BHSportMainSecView = {
        let view = BHSportMainSecView.loadFromXib()
        return view
    }()
    
    lazy var createTitleView: BHSportCreateTitleView = {
        let view = BHSportCreateTitleView.init(frame: CGRect(x: 0, y: 0, width: UIScreen.width, height: UIScreen.height))
        view.delegate = self
        return view
    }()
    
    lazy var tableView: UITableView = {
        let view = UITableView.buildTableView(style: .plain)
        view.delegate = self
        view.dataSource = self
        view.backgroundColor = .white
        view.register(UINib.init(nibName: "BHSportInGoingCell", bundle: nil), forCellReuseIdentifier: "BHSportInGoingCell")
        view.register(UINib.init(nibName: "BHSportEndStateCell", bundle: nil), forCellReuseIdentifier: "BHSportEndStateCell")

        return view
    }()

    // 0未开始 1进行中  2已结束
    fileprivate var type: Int = 0
    
    var sportTargetArray: [BHSportTargetModel] = []
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        self.page = 1
        self.queryService()
    }
    override func viewDidLoad() {
        super.viewDidLoad()

        self.bh_navigationBar.title_label.text = "运动"
        self.bh_navigationBar.rightBtn.isHidden = false
        self.bh_navigationBar.rightBtn.setTitle("运动记录", for: .normal)
        self.bh_navigationBar.rightBtn.setTitleColor(.color_666666, for: .normal)
        self.bh_navigationBar.rightBtn.titleLabel?.font  = .systemFont(ofSize: 14, weight: .medium)
        
        self.view.addSubview(self.createTitleView)
        self.view.addSubview(self.headerView)
        self.secView.frame = CGRect(x: 0, y: self.headerView.bh_bottom, width: UIScreen.width, height: BHSportMainSecView.height)
        self.view.addSubview(self.secView)
        
        self.tableView.frame = CGRect(x: 0, y: self.secView.bh_bottom, width: UIScreen.width, height: UIScreen.height-self.secView.bh_bottom)
        
        self.view.addSubview(self.tableView)
        self.secView.didChangeIndexActBlock = { [weak self] index in
            SVProgressHUD.show()
            self?.type = index
            self?.page = 1
            self?.queryService()
        }
        
        self.tableView.addRefresh { [weak self] in
            self?.page = 1
            self?.queryService()
        }
        self.tableView.addloadMore { [weak self] in
            self?.page += 1
            self?.queryService()
            
        }
    }
    

    override func rightBtnAction() {
        let recordVC = BHSportRecordViewController.init()
        self.navigationController?.pushViewController(recordVC, animated: true)
    }

}

extension BHSportMainViewController: BHSportCreateTitleViewDelegate {
    func didCreateTitleConfirm(text: String, type: Int) {
        if text.isEmpty == true {
            return
        }
        let bc = BHSportTimerViewController.init(nibName: "BHSportTimerViewController", bundle: nil)
        bc.sportType = type
        bc.sportTitle = text
        self.navigationController?.pushViewController(bc, animated: true)
        self.createTitleView.clear()
    }
}

extension BHSportMainViewController: BHSportMainHeaderViewDelegate {
    func didSportHeaderSelectTypeBegain(type: Int) {
        if type == 0 {
            let createVC = BHSportCreateClockViewController.init()
            self.navigationController?.pushViewController(createVC, animated: true)
        }else {
            self.createTitleView.type = type
            self.createTitleView.show()
        }
    }
}
extension BHSportMainViewController: UITableViewDataSource {
    func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        
        return self.sportTargetArray.count
    }
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        if self.type == 1 {
            return 130
        }else {
            return 80
        }
    }
  
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let model = self.sportTargetArray[indexPath.row]
        BHRouter.shared.bh_goSportSignDetail(targetId: model.targetId)
    }
}

extension BHSportMainViewController: UITableViewDelegate {
  
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        if self.type == 1 {
            let cell = tableView.dequeueReusableCell(withIdentifier: "BHSportInGoingCell", for: indexPath) as! BHSportInGoingCell
            let model = self.sportTargetArray[indexPath.row]
            cell.model = model
            cell.haveAMarkBtn.addBtnAction(action: { (_) in
                BHRouter.shared.bh_goSportSignDetail(targetId: model.targetId)
            }, for: .touchUpInside)
            return cell
        }else {
            let cell = tableView.dequeueReusableCell(withIdentifier: "BHSportEndStateCell", for: indexPath) as! BHSportEndStateCell
            let model = self.sportTargetArray[indexPath.row]
            cell.model = model
            cell.shareBtn.isHidden = self.type != 2
            return cell
        }
    }
}
extension BHSportMainViewController {
    func queryService()  {
        
        let dic = self.appendDic()
        let manager = BHHTTPClient.init()
        manager.get(url: String.sport_main_target_list_url, paramters: dic) {[unowned self] (success, errorMsg, responseDic) in
            SVProgressHUD.dismiss()
            self.tableView.endRefresh()
            self.tableView.endLoading()
            if success == true {
                let result = BHJsonTool.decodeDicFromDic(dic: responseDic, key: "result")
                let total = BHJsonTool.decodeIntFromDic(dic: result, key: "total")
                if self.page == 1 {
                    self.tableView.endLoadWithNoMoreData(false)
                    if self.sportTargetArray.count != 0 {
                        self.sportTargetArray.removeAll()
                    }
                }
                
                let records = BHJsonTool.decodeArrayFromDic(dic: result, key: "records")
                for item in records {
                    let model = BHSportTargetModel.init()
                    model.parseDic(item as! [String:Any])
                    self.sportTargetArray.append(model)
                }
                
                self.tableView.reloadData()
                if self.sportTargetArray.count >= total {
                    self.tableView.endLoadWithNoMoreData(true)
                }
                
            }else {
                BHToast.toast(text: errorMsg)
                if self.page > 1 {
                    self.page -= 1
                }
            }
        }
    }
    
    func appendDic() -> [String:Any] {
        var dic: [String:Any] = [:]
        dic["pageNo"] = self.page
        dic["pageSize"] = 10
        dic["status"] = self.type
        return dic
    }
}

